package com.example.handlemessage;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import java.lang.ref.WeakReference;

public class MainActivity extends AppCompatActivity {

    private MyHandler mainHandler = new MyHandler(this);

    private WorkerThread workerThread;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 启动子线程执行任务
        workerThread = new WorkerThread();
        workerThread.start(); // 启动子线程

        // 延迟 2 秒后，主线程给子线程发送消息
        new Thread(() -> {
            try {

                Thread.sleep(2000); // 模拟主线程等待子线程完成
                // 主线程发送消息到子线程
                if (workerThread != null && workerThread.workerHandler != null) {
                    Message msgToWorker = workerThread.workerHandler.obtainMessage();
                    msgToWorker.what = 1;
                    msgToWorker.obj = "主线程消息：子线程开始执行任务";
                    workerThread.workerHandler.sendMessage(msgToWorker); // 发送消息到子线程
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();


        /*// 启动子线程执行任务
        new Thread(() -> {
            // 模拟耗时操作
            try {
                Thread.sleep(2000); // 模拟耗时操作
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // 子线程任务完成后，通过主线程的 Handler 更新 UI
            Message msg = mainHandler.obtainMessage();
            msg.what = 1;
            msg.obj = "任务完成，UI 已更新！";
            mainHandler.sendMessage(msg);
        }).start();*/
    }

    // 使用 WeakReference 防止内存泄漏
    private static class MyHandler extends Handler {
        private final WeakReference<MainActivity> activityReference;

        MyHandler(MainActivity activity) {
            super(Looper.getMainLooper()); // 显式指定主线程的 Looper
            activityReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            MainActivity activity = activityReference.get();
            if (activity != null) {
                if (msg.what == 1) {
                    String result = (String) msg.obj;
                    TextView textView = activity.findViewById(R.id.textView);
                    textView.setText(result); // 更新 UI
                }
            }
        }
    }


    // 子线程的任务处理
    private class WorkerThread extends Thread {
        private WorkerHandler workerHandler;

        @Override
        public void run() {
            // 子线程需要准备 Looper 和 Handler
            Looper.prepare(); // 子线程准备 Looper
            workerHandler = new WorkerHandler(); // 创建子线程的 Handler

            // 子线程进入消息循环，等待处理消息
            Looper.loop(); // 开始消息循环
        }

        // 子线程的 Handler，用来处理主线程发送过来的消息
        private class WorkerHandler extends Handler {
            @Override
            public void handleMessage(@NonNull Message msg) {
                if (msg.what == 1) {
                    String message = (String) msg.obj;
                    // 子线程收到主线程的消息后执行某些操作
                    System.out.println("子线程收到消息: " + message);
                    // 可以在此处执行子线程的任务，或者向主线程发送结果
                    new Thread(() -> {
                        // 模拟耗时操作
                        try {
                            Thread.sleep(2000); // 模拟耗时操作
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        // 子线程任务完成后，通过主线程的 Handler 更新 UI
                        Message msgFromChild = mainHandler.obtainMessage();
                        msgFromChild.what = 1;
                        msgFromChild.obj = "任务完成，UI 已更新！";
                        mainHandler.sendMessage(msgFromChild);
                    }).start();
                }
            }
        }
    }

}